/**
 * 
 */
package com.sqltojson.dao;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import com.google.common.collect.Lists;
import com.sqltojson.core.Query;
import com.sqltojson.exception.QueryDaoException;
import com.sqltojson.util.Util;

/**
 * Recuperation des requetes en fichier.
 */
public final class QueryDao {

	/**
	 * 
	 */
	public QueryDao() {
	}

	/**
	 * @param name
	 *            le nom de la requete a recuperer
	 * @return la requete
	 * @throws QueryServiceException
	 */
	public Query get(String name) throws QueryDaoException {
		try {
			return read(name);
		} catch (JAXBException e) {
			throw new QueryDaoException(String.format(
					"Probleme avec la requete '%s'", name));
		}
	}

	/**
	 * Lecture de la configuration du query.
	 * 
	 * @return la configuration du query
	 * @throws JAXBException
	 */
	private static Query read(final String name) throws JAXBException {
		final InputStream resourceAsStream = Util.getResourceAsStream(name);
		return resourceAsStream == null ? null : read(resourceAsStream);
	}

	/**
	 * @param inputStream
	 *            representant le query
	 * @return les informations sur le query
	 * @throws JAXBException
	 */
	private static Query read(InputStream inputStream) throws JAXBException {
		final JAXBContext context = JAXBContext.newInstance(Query.class);
		return (Query) context.createUnmarshaller().unmarshal(inputStream);
	}
}
